﻿CREATE PROCEDURE [dbo].[DepartmentUsersDelete]
(
	@Original_Id int,
	@Original_MD datetime
)
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int, @strUserName varchar(50)
	SET NOCOUNT ON

SELECT @strUserName = [Login] FROM [CD].[DepartmentUsers] 
WHERE Id = @Original_Id AND MD = @Original_MD

IF @@rowcount <> 1 
BEGIN
	SET @intErrCode = 1
	SET @strMsg = N'Пользователь с кодом %d не найден в базе данных!'
	RAISERROR (@strMsg, 11, 1, @Original_Id)
	RETURN @intErrCode
END

IF @Original_Id = 0 
BEGIN
	SET @intErrCode = 2
	SET @strMsg = N'Нельзя удалять пользователя с кодом 0!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

BEGIN TRAN

EXECUTE('DROP USER [' + @strUserName + ']')
SET @intErrCode = @@error
IF @intErrCode <> 0 
BEGIN
	ROLLBACK TRAN
	RETURN @intErrCode
END

IF EXISTS ( SELECT Id FROM CA.Documents WHERE Id = @Original_Id)
BEGIN
	SET NOCOUNT OFF;
	UPDATE [CD].[DepartmentUsers] SET 
	Login = 'Удалён ' + Login,
	MD = getdate(),
	MW = SYSTEM_USER
	WHERE Id = @Original_Id
END ELSE BEGIN
	SET NOCOUNT OFF;
	DELETE FROM [CD].[DepartmentUsers] WHERE Id = @Original_Id
END

COMMIT TRAN

RETURN 0

